package com.vshop.controller.login;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.vshop.entity.comentity.PartnerInfo;
import com.vshop.entity.interfacerequest.ExceptionRequest;
import com.vshop.entity.interfacerequest.partnerlogin.request.RequestPartnerLogin;
import com.vshop.entity.interfacerequest.partnerlogin.request.RequestPartnerLoginData;
import com.vshop.entity.interfacerequest.partnerlogin.request.RequestPartnerLoginTradeData;
import com.vshop.entity.interfacerequest.partnerlogin.response.ResponsePartnerLogin;
import com.vshop.entity.interfacerequest.partnerlogin.response.ResponsePartnerLoginData;
import com.vshop.service.PartnerInfoService;
import com.vshop.service.SequenceService;
import com.vshop.utils.Md5Encrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 商家登录
 *
 * @author lm
 * @date 2019/03/07
 */
@RestController
@Api(description = "商家登录")
@Slf4j
public class PartnerLoginController {
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private PartnerInfoService partnerInfoService;
    @Autowired
    private HttpSession session;

    @CrossOrigin
    @PostMapping(value = "partnerLogin", produces = "application/json;charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "首页", response = ResponsePartnerLogin.class)
    public String home(@ApiParam @RequestBody RequestPartnerLogin request) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());

        String openId = (String) session.getAttribute("openId");
        log.info("从session取出的openId是：" + session.getAttribute("openId"));

        //3,定义要回复的内容
        String jsonString;
        ExceptionRequest utils = new ExceptionRequest();

        String requestStr = JSON.toJSONString(request);
        if (requestStr == null) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            log.info("前端请求报文是：" + requestStr);
            RequestPartnerLogin requestPackage = JSONArray.parseObject(requestStr, RequestPartnerLogin.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                log.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                log.info("请求的签名是：" + requestSign);
                RequestPartnerLoginData requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    log.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String partnerCode = requestData.getPartnerCode();
                    String tradeTime = requestData.getTradeTime();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    String version = requestData.getVersion();
                    RequestPartnerLoginTradeData requestTradeData = requestData.getTradeData();

                    if (StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(partnerCode) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType) || lang == null || version == null || requestTradeData == null) {
                        log.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {

                        String account = requestTradeData.getAccount();
                        String password = requestTradeData.getPassword();

                        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
                            log.info("请求报文不合法:tradeData参数不合法");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            // 将请求体json转成String// 将Str拿去计算签名
                            String str = JSON.toJSONString(requestData);
                            String sign = utils.calculateSignature(str);
                            log.info("计算的签名是：" + sign);

                            if (lang.equals("cn") || StringUtils.isBlank(lang)) {
                                if (!requestSign.equalsIgnoreCase(sign)) {
                                    log.info("签名验证失败！");
                                    jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, tradeType, "0001", "签名有误，请确认签名！");
                                    return jsonString;
                                } else {//签名验证通过
                                    //用account和password去数据库比对查询，看看结果是不是对的
                                    PartnerInfo info = partnerInfoService.queryPartnerAccountAndPassword(partnerCode, account, password);
                                    if (info != null) {
                                        if (info.getPartnerCode() == null || !partnerCode.equals(partnerCode)) {
                                            //数据库没有这个账号跟密码组合
                                            log.info("获取信息为null，不允许登录");
                                            jsonString = utils.illegalLogin(connSeqNo, curtime, tradeType);
                                            return jsonString;

                                        } else {
                                            //数据库有当前账号和密码，允许登录
                                            log.info("允许登录" + info.getPartnerCode());
                                            ResponsePartnerLoginData data = new ResponsePartnerLoginData();
                                            data.setConnSeqNo(connSeqNo);
                                            data.setPartnerCode(info.getPartnerCode());
                                            data.setTradeType(tradeType);
                                            data.setTradeTime(curtime);
                                            data.setTradeRstCode("0000");
                                            data.setTradeRstMessage("成功");
                                            data.setOpenId(openId);

                                            ResponsePartnerLogin partnerLogin = new ResponsePartnerLogin();
                                            partnerLogin.setData(data);
                                            partnerLogin.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));

                                            // 返回给调用者的报文
                                            jsonString = JSON.toJSONString(partnerLogin);
                                            log.info("响应报文：" + jsonString);
                                            return jsonString;

                                        }


                                    } else {
                                        log.info("获取信息为null，不允许登录");
                                        jsonString = utils.illegalLogin(connSeqNo, curtime, tradeType);
                                        return jsonString;
                                    }
                                }

                            } else {//英文
                                if (!requestSign.equalsIgnoreCase(sign)) {
                                    log.info("签名验证失败！");
                                    jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, tradeType, "0001", "签名有误，请确认签名！");
                                    return jsonString;
                                } else {//签名验证通过
                                    //用account和password去数据库比对查询，看看结果是不是对的
                                    PartnerInfo info = partnerInfoService.queryPartnerAccountAndPassword(partnerCode, account, password);
                                    if (info != null) {
                                        if (info.getPartnerCode() == null || !partnerCode.equals(partnerCode)) {
                                            //数据库没有这个账号跟密码组合
                                            log.info("获取信息为null，不允许登录");
                                            jsonString = utils.illegalLoginEN(connSeqNo, curtime, tradeType);
                                            return jsonString;

                                        } else {
                                            //数据库有当前账号和密码，允许登录
                                            log.info("允许登录" + info.getPartnerCode());
                                            ResponsePartnerLoginData data = new ResponsePartnerLoginData();
                                            data.setConnSeqNo(connSeqNo);
                                            data.setPartnerCode(info.getPartnerCode());
                                            data.setTradeType(tradeType);
                                            data.setTradeTime(curtime);
                                            data.setTradeRstCode("0000");
                                            data.setTradeRstMessage("success");
                                            data.setOpenId(openId);

                                            ResponsePartnerLogin partnerLogin = new ResponsePartnerLogin();
                                            partnerLogin.setData(data);
                                            partnerLogin.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));

                                            // 返回给调用者的报文
                                            jsonString = JSON.toJSONString(partnerLogin);
                                            log.info("响应报文：" + jsonString);
                                            return jsonString;

                                        }


                                    } else {
                                        log.info("获取信息为null，不允许登录");
                                        jsonString = utils.illegalLoginEN(connSeqNo, curtime, tradeType);
                                        return jsonString;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
